package cn.lijiguo.concurrency.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 无界线程池 CachedThreadPool
 * <p>
 * 无界线程池的创建过程是可定制的，如果想自定义现成的创建方式，
 *  可以使用 newCachedThreadPool(ThreadFactory) 构造, 允许提供自定义的线程工厂
 */
@Slf4j
public class CachedThreadPoolWithCustomThreadFactory {

    public static void main(String[] args) {
        // 创建自定义线程工厂
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("CustomThread-" + thread.getId());
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.setDaemon(false);
                return thread;
            }
        };

        // 创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool(threadFactory);

        // 提交任务
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            executorService.submit(() -> {
                log.info("Task " + taskId + " is executing by " + Thread.currentThread().getName());
                try {
                    // 模拟任务执行
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    log.error(e.getMessage(), e);
                    Thread.currentThread().interrupt();
                }
            });
        }

        // 关闭线程池
        executorService.shutdown();
    }
}
